/**
 *Socket基类
 * 
 *该类为Socket的基类，
 *内部仅重写和对服务器的响应做了简单的判断
 *@Jacku
 **/
package xnet.core
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.ObjectEncoding;
	import flash.net.Socket;
	import flash.system.Security;
	import flash.utils.ByteArray;
	
	import xnet.SocketManager;
	import xnet.events.SocketEvent;

	
	public class SocketBase extends Socket
	{

		/**主方法入口
		 *@param host 
		 *@param port
		 **/
		public function SocketBase()
		{
			/**AMF3只在写Object时才会用到,用于约定通信协议**/
			this.objectEncoding = ObjectEncoding.AMF3;
			/**监听Socket加载过程中的所有事件**/
			this.addEventListener(Event.CONNECT , onConnect);
			this.addEventListener(Event.CLOSE , onClose);
			this.addEventListener(IOErrorEvent.IO_ERROR , onIOError);
			this.addEventListener(SecurityErrorEvent.SECURITY_ERROR , onSecurityError);
			this.addEventListener(ProgressEvent.SOCKET_DATA , onData);
		}
		
		/**重写connect方法，其中加入策略文件的加载**/
		override public function connect(host:String , port:int):void
		{
			super.connect(host , port);
		}
		
		/**关闭当前socket连接**/
		override public function close():void
		{
			if(this.connected)
			{
				super.close();
			}
		}
		
		/**对socket数据的更新进行监听操作**/
		private function onData(e:ProgressEvent):void
		{
			SocketManager.instance.dispatchEvent(new SocketEvent(SocketEvent.RECEIEVED));
		}
		
		private function onConnect(e:Event):void
		{
			SocketManager.instance.dispatchEvent(new SocketEvent(SocketEvent.CONNECT));
			trace('连接socket服务器成功！');
		}
		
		private function onClose(e:Event):void
		{
			SocketManager.instance.dispatchEvent(new SocketEvent(SocketEvent.CLOSE));
			trace('断开了和socket服务器的连接！');
		}
		
		private function onIOError(e:IOErrorEvent):void
		{
			trace('连接服务器失败，请稍候操作');
		}
		
		private function onSecurityError(e:SecurityErrorEvent):void
		{
			trace('发生沙箱安全错误！');
		}
	}
}